// 引入数据库模块
const { connection, requsetQuery } = require('../database/db')
const bcrypt = require('bcryptjs'); //加密模块
const salt = bcrypt.genSaltSync(10);
// 生成图片验证码
const svgCaptcha = require('svg-captcha')
    //引入token模块
const JWT = require('../utils/token');
// 随机生成字符串
const stringRandom = require('string-random');
//1. 定义一个临时的图片验证码
var tempcaptcha = null;
//2.定义一个临时的短信验证码
var tempcode = null;
//3.定义一个临时的手机号
var tempphone = null;
// 格式化时间
const moment = require('moment');
//http://localhost:3000/user/userlist?page=1&size=10
exports.UserList = async(req, res) => {
    // get 传值通过req.query 
    let page = req.query.page || 1; //设置页
    let size = req.query.size || 10; //设置一页几条数据
    let sort = req.query.size || "ASC"
    let index = (page - 1) * size
    let countSql = ` SELECT count(*) FROM users WHERE is_show=1`
    let countResult = await requsetQuery(countSql)
    let total = countResult[0]['count(*)'];
    // 列表sql
    let userSql = `SELECT * FROM users WHERE is_show=1 ORDER BY sort ${sort} LIMIT ${index},${size}`
    let userListData = await requsetQuery(userSql);
    let totalPage = Math.ceil(total / size);
    res.json({
        status: 200,
        total: total,
        page: page,
        size: size,
        sort: sort,
        totalpage: totalPage,
        data: userListData
    })
}


// 用户注册
//http://localhost:3000/user/register

exports.UserRegister = (req, res) => {
    let user_name = req.body.user_name;
    let phone = req.body.phone;
    let user_password = req.body.user_password;
    //格式化时间
    let nowTime = moment().format("YYYY-MM-DD HH:mm:ss");
    //需求：用户名和手机号不能重复添加
    //查询用户名是否存在
    let user_name_sql = `SELECT user_name FROM users WHERE user_name=? AND is_show=1`
    connection.query(user_name_sql, user_name, (err, result_name) => {
        if (err) {
            return res.json({
                msg: "用户注册失败1",
                status: 1001,
                data: err
            })
        }
        //如果result_name是一个空数组，说明用户名不存在，可用
        if (result_name == "") {
            //如果条件成立，用户名可用
            //需要再判断手机号是否存在
            let phone_sql = `SELECT phone FROM users WHERE phone=? AND is_show=1`
            connection.query(phone_sql, phone, (err, result_phone) => {
                if (err) {
                    return res.json({
                        msg: "用户注册失败2",
                        status: 1002,
                        data: err
                    })
                }
                if (result_phone == "") {
                    //如果条件成立说明手机号可用
                    //用户名也是可用的，可以写入数据库了
                    let register_sql = `insert into users set user_name=?,user_password=?,phone=?,is_show=1,create_time='${nowTime}'`
                    let hashPassword = bcrypt.hashSync(user_password, salt)
                    connection.query(register_sql, [user_name, hashPassword, phone], (err, data) => {
                        if (err) {
                            return res.json({
                                msg: "用户注册失败3",
                                status: 1003,
                                data: err
                            })
                        }
                        if (data.affectedRows == 1) {
                            return res.json({
                                msg: "恭喜你!用户注册成功",
                                status: 200,
                                data: data
                            })
                        } else {
                            return res.json({
                                msg: "用户注册失败4",
                                status: 1004,
                                data: err
                            })
                        }
                    })
                } else {
                    return res.json({
                        msg: "该手机号存在,请换手机号注册",
                        status: 1005,
                    })
                }
            })
        } else {
            return res.json({
                msg: "该用户名存在,请换用户名注册",
                status: 1006,
            })
        }
    })
}


//用户登录
exports.Login = (req, res) => {
    let user_name = req.body.user_name;
    let user_password = req.body.user_password;
    let user_name_sql = `SELECT user_name,user_password FROM users WHERE user_name=? AND is_show=1`

    connection.query(user_name_sql, [user_name], (err, data) => {
        if (err) {
            return res.json({
                msg: "数据库查询失败",
                status: 5001,
                data: err
            })
        }
        if (data.length == 0) {
            return res.json({
                // 如果条件成立说明用户名不存在
                msg: "该用户不存在，请注册",
                status: 404,
            })
        } else {
            console.log(data);
            let check_user_password = bcrypt.compareSync(req.body.user_password, data[0].user_password)
            if (!check_user_password) {
                return res.json({
                    // 如果条件成立说明密码错误
                    msg: "密码错误，请输入正确密码",
                    status: 5001,
                })
            } else {
                let token = JWT.createToken({
                    user_name: user_name,
                    isLogin: true
                })
                JWT.checkToken(token).then(result => {
                    console.log(result);
                })
                return res.json({
                    msg: "登录成功",
                    status: 200,
                    token: token,
                    data: data
                })
            }
        }
    })

}

// 图片验证码
exports.svgCaptcha = (req, res) => {
    var captcha = svgCaptcha.create({
        size: 4,
        ignoreChars: '0o1i',
        noise: 2,
        color: true,
        background: "#ccc"
    });
    res.type('svg');
    tempcaptcha = captcha.text.toLowerCase()
    res.status(200).send(captcha.data);
}

// 短信验证码控制器
exports.MessageCode = (req, res) => {
    //第一步：输入正确的手机号
    //第二步：点击获取验证码按钮，发起请求
    //第三步：发送短信内容+随机的验证码
    //req.body {phone:"13673618137"}
    let codeStr = ("000000" + Math.floor(Math.random() * 999999)).slice(-6);
    tempphone = req.body.phone;
    tempcode = codeStr;
    console.log(tempcode);
    res.json({
        msg: '发送成功',
        status: 200,
        code: codeStr
    })

}

// 短信登录接口

exports.PhoneLogin = async(req, res) => {
    //post来提交数据
    //req.body   {phone:"17634756361","captcha":"abcc","code":"859966"}
    //在该接口中验证短信验证码和图片验证码
    // console.log(tempcaptcha);
    // console.log(tempcode);
    // console.log(tempphone);
    // 获取用户提交的数据
    let phone = req.body.phone;
    let code = req.body.code;
    let captcha = req.body.captcha.toLowerCase();
    if (tempcaptcha != captcha) {
        return res.json({
            msg: "图形验证码错误",
            status: 1001
        })
    } else if (tempcode != code) {
        return res.json({
            msg: "短信验证码错误",
            status: 1002
        })
    } else if (tempphone != phone) {
        return res.json({
            msg: "手机号错误",
            status: 1003
        })
    } else {
        //说明上面条件都成立
        //对比数据库判断手机号是否存在
        //1.手机号不存在---将该手机号注册到数据库
        let phone_sql = `SELECT * FROM users where phone=? and is_show=1`
        let phone_result = await requsetQuery(phone_sql, phone)

        if (phone_result.length == 0) {
            //如果条件成立说明手机号不存在，需要将手机号注册到数据库
            let user_name = "ty_" + stringRandom(10) + new Date().getTime();
            let nowTime = moment().format("YYYY-MM-DD HH:mm:ss");
            let hashPassword = bcrypt.hashSync("123456", salt);
            let userSql = `INSERT INTO users (user_name,user_password,is_show,phone,create_time) VALUES("${user_name}","${hashPassword}","1","${phone}","${nowTime}")`
            let result = await requsetQuery(userSql)
            if (result.affectedRows == 1) {
                return res.json({
                    msg: "登录成功",
                    status: 200,
                    data: result
                })
            } else {
                return res.json({
                    msg: "服务器错误",
                    status: 5001
                })
            }
        } else {
            return res.json({
                msg: "登录成功",
                status: 200,
                data: phone_result
            })
        }
        //2.手机号存在---直接登录
    }
}